/*
 * @Author: tyz
 * @Date: 2021-06-24 16:02:42
 * @LastEditTime: 2021-06-24 17:13:09
 * @Description: local策略
 * @FilePath: \nest_demo\src\module\auth\local.strategy.ts
 */
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';

/*
    * 自定义local策略步骤：
    *   1. 上面的import都需要引入下来
    *   2. 自定义'LocalStrategy'通过继承'PassportStrategy'来实现自定义策略，另外还需要传递'Strategy'参数
    *   3. 定义validate方法
*/

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy){
    constructor(private readonly authService:AuthService){
        super()
    };

    /*
        * 注意：
        *   1. 这里需要异步操作，因为真实项目用户名密码验证是需要异步查询数据库的
    */
    async validate(username:string, password:string):Promise<any>{
        console.log("鉴权：",username, password);
        const user = await this.authService.findUserInfo(username,password);
        if(!user){
            throw new HttpException(
                {message:'用户不存在'},
                HttpStatus.BAD_REQUEST
            );
        }
        return user;
    }
};